package edu.ynu.se.xiecheng.achitectureclass.common.service;

import edu.ynu.se.xiecheng.achitectureclass.common.entity.Image;
import edu.ynu.se.xiecheng.achitectureclass.common.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.common.repository.ImageRepository;
import edu.ynu.se.xiecheng.achitectureclass.common.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.util.StreamUtils;
import org.springframework.core.io.UrlResource;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.net.URI;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CameraService {

    @Autowired
    private RestTemplate restTemplate; // 用于发送 HTTP 请求
    @Autowired
    private UserRepository userRepository; // 用于获取用户信息
    @Autowired
    private ImageRepository imageRepository; // 用于保存图片数据到数据库


    // 获取所有抓拍的图片，按抓取时间排序
    public List<Image> getAllCapturedImages() {
        // 查询数据库中的所有图片，并按抓取时间进行降序排序（最新的图片排在前面）
        return imageRepository.findAll();
    }

    // 根据用户 ID 获取云平台的 accessToken
    public String getAccessToken(String  userId) {
        User user = userRepository.findById(userId).orElseThrow(() -> new RuntimeException("User not found"));
        return user.getCloudToken(); // 获取存储在数据库中的 cloud_token
    }

    // 抓拍摄像头图片并保存到本地
    public void captureCameraImage(String userId, String deviceSerial) throws IOException {
        String accessToken = getAccessToken(userId);

        if (accessToken == null) {
            throw new RuntimeException("Access token not found for the user");
        }

        // 定义抓拍接口的 URL
        String url = "https://open.ys7.com/api/lapp/device/capture";

        // 请求参数
        String requestBody = String.format("accessToken=%s&deviceSerial=%s&channelNo=1&quality=2", accessToken, deviceSerial);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 创建请求实体
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        try {
            // 发送 POST 请求
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                // 解析响应，获取图片地址
                String responseBody = response.getBody();
                if (responseBody != null) {
                    // 使用简单的字符串处理，实际应该使用 JSON 解析库（如 Jackson 或 Gson）
                    int picUrlIndex = responseBody.indexOf("\"picUrl\":\"") + 10;
                    int picUrlEndIndex = responseBody.indexOf("\"", picUrlIndex);
                    String picUrl = responseBody.substring(picUrlIndex, picUrlEndIndex);

                    // 下载图片并保存到本地
                    String localImagePath = downloadAndSaveImage(picUrl);
                    // 将图片路径和抓取时间保存到数据库
                    saveImageToDatabase(localImagePath);
                }
            } else {
                throw new RuntimeException("Failed to capture image from camera");
            }
        } catch (Exception e) {
            throw new RuntimeException("Error occurred while capturing image", e);
        }
    }

    // 下载图片并保存到本地
    private String downloadAndSaveImage(String picUrl) throws IOException {
        URI uri;

        // 判断 URL 是绝对路径还是相对路径
        if (picUrl.startsWith("http://") || picUrl.startsWith("https://")) {
            // 如果 picUrl 是完整的网络 URL
            uri = URI.create(picUrl);
        } else {
            // 如果 picUrl 是相对路径（本地路径）
            Path absolutePath = Paths.get(picUrl).toAbsolutePath(); // 将相对路径转换为绝对路径
            uri = absolutePath.toUri(); // 转换为 URI
        }

        // 下载图片并保存到文件
        UrlResource urlResource = new UrlResource(uri);
        Path path = Paths.get("camera_images/capture_" + System.currentTimeMillis() + ".jpg");

        try (InputStream inputStream = urlResource.getInputStream()) {
            // 定义本地保存路径
            Files.createDirectories(path.getParent()); // 创建父目录
            Files.copy(inputStream, path); // 保存文件

            System.out.println("Image saved to: " + path.toString());
        }
        return path.toString(); // 返回保存图片的本地路径
    }

    // 保存图片路径和抓取时间到数据库
    private void saveImageToDatabase(String imagePath) {
        Image image = new Image(imagePath, LocalDateTime.now());
        imageRepository.save(image); // 将图片数据保存到数据库
        System.out.println("Image data saved to database with path: " + imagePath);
    }
}
